import { message, Popconfirm, Tooltip, Table, Space, Divider } from "antd";
import { useEffect } from "react";
import { useModel } from "umi";
import { Button, ButtonGroup, Card as SemiCard } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconDelete, IconEdit, IconEyeOpened } from "@douyinfe/semi-icons";
import { useReactive } from "ahooks";
import { format } from "timeago.js";

import { FindByIecType, DeleteCategory, UpdateCategoryAuth } from "../../_graphql/resources";

import AddIncomeExpenseCategory from "../../_modals/income_expense_category/addCategory";
import EditIncomeExpenseCategory from "../../_modals/income_expense_category/editCategory";

const { Column } = Table;

const RevenueExpenditureCategory = () => {
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent, setModalStyle } = useModel("global.modal");
    const { windowInnerHeight, graphqlFetchPlatform, UTCTimeToLocal } = useModel("global");
    const { baseInfo } = useModel("person.info");

    const state = useReactive({
        submitLoading: false,
        incomeLoading: false,
        expenseLoading: false,
        incomeCategories: [],
        expenseCategories: [],
    });

    const loadIncomeCategory = async () => {
        state.incomeLoading = true;
        let res = await graphqlFetchPlatform({ query: FindByIecType, variables: { iecType: "收入" } });
        state.incomeCategories = res?.a?.nodes || [];
        state.incomeLoading = false;
    };

    const loadExpenseCategory = async () => {
        state.expenseLoading = true;
        let res = await graphqlFetchPlatform({ query: FindByIecType, variables: { iecType: "支出" } });
        state.expenseCategories = res?.a?.nodes || [];
        state.expenseLoading = false;
    };

    useEffect(() => {
        loadIncomeCategory();
        loadExpenseCategory();
    }, []);

    const openAddCategoryModal = (type) => {
        setModalTitle("添加收支类别");
        setModalWidth(500);
        if (type === "收入") setModalComponent(<AddIncomeExpenseCategory type={type} categories={state.incomeCategories} reloadData={loadIncomeCategory} />);
        else setModalComponent(<AddIncomeExpenseCategory type={type} categories={state.expenseCategories} reloadData={loadExpenseCategory} />);
        setModalStyle({ top: 100 });
        setModalVisible(true);
    };

    const openEditCategoryModal = (type, record) => {
        setModalTitle("添加收支类别");
        setModalWidth(500);
        if (type === "收入") setModalComponent(<EditIncomeExpenseCategory record={record} categories={state.incomeCategories} reloadData={loadIncomeCategory} />);
        else setModalComponent(<EditIncomeExpenseCategory record={record} categories={state.expenseCategories} reloadData={loadExpenseCategory} />);
        setModalStyle({ top: 100 });
        setModalVisible(true);
    };

    const updateCategoryAuthState = async (type, iecUuid) => {
        state.submitLoading = true;
        let res = await graphqlFetchPlatform({
            query: UpdateCategoryAuth,
            variables: {
                iecUuid,
                iecAuth: { uuid: baseInfo.uuid, name: baseInfo.realName },
                iecAuti: new Date().getUTCTime(),
            },
        });
        if (res) {
            message.success("成功审核通过收入类别信息");
            type === "收入" ? loadIncomeCategory() : loadExpenseCategory();
        }
        state.submitLoading = false;
    };

    const deleteCategory = async (type, iecUuid) => {
        state.submitLoading = true;
        let res = await graphqlFetchPlatform({ query: DeleteCategory, variables: { iecUuid } });
        if (res) {
            message.success(`成功删除${type}类别信息`);
            type === "收入" ? loadIncomeCategory() : loadExpenseCategory();
        }
        state.submitLoading = false;
    };

    // 窗口头部：30，应用头：60，页头：59，操作区内边距：24，卡面头：51，卡面脚：56,修正值：4
    const cardBodyHeight = (windowInnerHeight - 30 - 60 - 48 - 10) / 2 - 56;

    return (
        <div style={{ padding: 10 }}>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}> 收入类别</span>}
                headerStyle={{ padding: "10px 14px" }}
                shadows="always"
                bordered={false}
                size="default"
                bodyStyle={{ padding: 0, height: cardBodyHeight }}
                style={{ marginBottom: 16 }}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconPlusCircle />} onClick={() => openAddCategoryModal("收入")}></Button>
                        <Button icon={<IconRefresh />} onClick={loadIncomeCategory}></Button>
                    </ButtonGroup>
                }
            >
                <Table loading={state.incomeLoading} dataSource={state.incomeCategories} rowKey="iecUuid" size="small" pagination={false} scroll={{ y: cardBodyHeight - 46 }}>
                    <Column title="类别编码" dataIndex="iecIdno" align="center" />
                    <Column title="类别名称" dataIndex="iecName" align="center" />
                    <Column
                        title="类别说明"
                        dataIndex="iecRemk"
                        align="center"
                        render={(_, r, i) =>
                            _ && (
                                <Tooltip title={_}>
                                    <IconEyeOpened />
                                </Tooltip>
                            )
                        }
                    />
                    <Column
                        title="创建时间"
                        dataIndex="iecCrti"
                        align="center"
                        render={(_, r, i) => _ && <Tooltip title={UTCTimeToLocal(_, "YYYY年MM月DD日 hh:ss:mm")}>{format(UTCTimeToLocal(_), "zh_CN")}</Tooltip>}
                    />
                    <Column
                        title="修改时间"
                        dataIndex="iecUpti"
                        align="center"
                        render={(_, r, i) => _ && <Tooltip title={UTCTimeToLocal(_, "YYYY年MM月DD日 hh:ss:mm")}>{format(UTCTimeToLocal(_), "zh_CN")}</Tooltip>}
                    />
                    <Column
                        title="审核状态"
                        dataIndex="iecStat"
                        align="center"
                        render={(_, r, i) =>
                            _ ? (
                                "已审核"
                            ) : (
                                <Popconfirm
                                    title="通过审核后，就不能更改类别名称啦，确认吗？"
                                    okButtonProps={{ loading: state.submitLoading }}
                                    onConfirm={() => updateCategoryAuthState("收入", r.iecUuid)}
                                >
                                    <a>待审核</a>
                                </Popconfirm>
                            )
                        }
                    />
                    <Column title="审核人" dataIndex="iecAuth" align="center" render={(_, r, i) => _.name} />
                    <Column
                        title="审核时间"
                        dataIndex="iecAuti"
                        align="center"
                        render={(_, r, i) => _ && <Tooltip title={UTCTimeToLocal(_, "YYYY年MM月DD日 hh:ss:mm")}>{format(UTCTimeToLocal(_), "zh_CN")}</Tooltip>}
                    />
                    <Column
                        title="来源"
                        dataIndex="iecFrom"
                        align="center"
                        render={(_, r, i) => (
                            <Tooltip title={(_.organizationName ? _.organizationName + " - " : "") + _.personName + " 上传于 " + format(UTCTimeToLocal(_.uploadTime), "zh_CN")}>
                                <IconEyeOpened />
                            </Tooltip>
                        )}
                    />
                    <Column
                        title="操作"
                        align="center"
                        width={140}
                        render={(_, r) => (
                            <Space split={<Divider type="vertical" />}>
                                <a onClick={() => openEditCategoryModal("收入", r)}>
                                    <IconEdit />
                                </a>
                                {!r.iecStat && (
                                    <Popconfirm
                                        placement="topRight"
                                        title="确认要删除该收入类别吗？"
                                        okButtonProps={{ loading: state.submitLoading }}
                                        onConfirm={() => deleteCategory("收入", r.iecUuid)}
                                    >
                                        <a>
                                            <IconDelete style={{ color: "#E91E63" }} />
                                        </a>
                                    </Popconfirm>
                                )}
                            </Space>
                        )}
                    />
                </Table>
            </SemiCard>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>支出类别</span>}
                headerStyle={{ padding: "10px 14px" }}
                shadows="always"
                bordered={false}
                size="default"
                bodyStyle={{ padding: 0, height: cardBodyHeight }}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconPlusCircle />} onClick={() => openAddCategoryModal("支出")}></Button>
                        <Button icon={<IconRefresh />} onClick={loadExpenseCategory}></Button>
                    </ButtonGroup>
                }
            >
                <Table loading={state.expenseLoading} dataSource={state.expenseCategories} rowKey="iecUuid" size="small" pagination={false} scroll={{ y: cardBodyHeight - 46 }}>
                    <Column title="类别编码" dataIndex="iecIdno" align="center" />
                    <Column title="类别名称" dataIndex="iecName" align="center" />
                    <Column
                        title="类别说明"
                        dataIndex="iecRemk"
                        align="center"
                        render={(_, r, i) =>
                            _ && (
                                <Tooltip title={_}>
                                    <IconEyeOpened />
                                </Tooltip>
                            )
                        }
                    />
                    <Column
                        title="创建时间"
                        dataIndex="iecCrti"
                        align="center"
                        render={(_, r, i) => _ && <Tooltip title={UTCTimeToLocal(_, "YYYY年MM月DD日 hh:ss:mm")}>{format(UTCTimeToLocal(_), "zh_CN")}</Tooltip>}
                    />
                    <Column
                        title="修改时间"
                        dataIndex="iecUpti"
                        align="center"
                        render={(_, r, i) => _ && <Tooltip title={UTCTimeToLocal(_, "YYYY年MM月DD日 hh:ss:mm")}>{format(UTCTimeToLocal(_), "zh_CN")}</Tooltip>}
                    />
                    <Column
                        title="审核状态"
                        dataIndex="iecStat"
                        align="center"
                        render={(_, r, i) =>
                            _ ? (
                                "已审核"
                            ) : (
                                <Popconfirm
                                    title="通过审核后，就不能更改类别名称啦，确认吗？"
                                    okButtonProps={{ loading: state.submitLoading }}
                                    onConfirm={() => updateCategoryAuthState("支出", r.iecUuid)}
                                >
                                    <a>待审核</a>
                                </Popconfirm>
                            )
                        }
                    />
                    <Column title="审核人" dataIndex="iecAuth" align="center" render={(_, r, i) => _.name} />
                    <Column
                        title="审核时间"
                        dataIndex="iecAuti"
                        align="center"
                        render={(_, r, i) => _ && <Tooltip title={UTCTimeToLocal(_, "YYYY年MM月DD日 hh:ss:mm")}>{format(UTCTimeToLocal(_), "zh_CN")}</Tooltip>}
                    />
                    <Column
                        title="来源"
                        dataIndex="iecFrom"
                        align="center"
                        render={(_, r, i) => (
                            <Tooltip title={(_.organizationName ? _.organizationName + " - " : "") + _.personName + " 上传于 " + format(UTCTimeToLocal(_.uploadTime), "zh_CN")}>
                                <IconEyeOpened />
                            </Tooltip>
                        )}
                    />
                    <Column
                        title="操作"
                        align="center"
                        width={140}
                        render={(_, r) => (
                            <Space split={<Divider type="vertical" />}>
                                <a onClick={() => openEditCategoryModal("支出", r)}>
                                    <IconEdit />
                                </a>
                                {!r.iecStat && (
                                    <Popconfirm
                                        placement="topRight"
                                        title="确认要删除该支出类别吗？"
                                        okButtonProps={{ loading: state.submitLoading }}
                                        onConfirm={() => deleteCategory("支出", r.iecUuid)}
                                    >
                                        <a>
                                            <IconDelete style={{ color: "#E91E63" }} />
                                        </a>
                                    </Popconfirm>
                                )}
                            </Space>
                        )}
                    />
                </Table>
            </SemiCard>
        </div>
    );
};

export default RevenueExpenditureCategory;
